<template>
  <CollapseContainer :title="t('routes.components.personalSetting.basicSetting')" :canExpan="false">
    <Row :gutter="24">
      <Col :span="14">
        <BasicForm @register="register" />
      </Col>
      <Col :span="10">
        <div class="change-avatar">
          <div class="mb-2">{{ t('routes.components.personalSetting.avatar') }}</div>
          <CropperAvatar
            :uploadApi="uploadApi"
            :value="avatar"
            :btnText="t('routes.components.personalSetting.updateAvatar')"
            :btnProps="{ preIcon: 'ant-design:cloud-upload-outlined' }"
            @change="updateAvatar"
            width="150"
          />
        </div>
      </Col>
    </Row>
    <Button type="primary" @click="handleSubmit">
      {{ t('routes.components.personalSetting.updateBasicInfo') }}
    </Button>
  </CollapseContainer>
</template>

<script lang="ts" setup>
  import { computed, onMounted } from 'vue';
  import { Button, Row, Col } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { CollapseContainer } from '/@/components/Container';
  import { CropperAvatar } from '/@/components/Cropper';
  import { useMessage } from '/@/hooks/web/useMessage';

  import headerImg from '/@/assets/images/header.jpg';
  import { accountInfoApi } from '/@/api/demo/account';
  import { baseSetschemas } from './data';
  import { useUserStore } from '/@/store/modules/user';
  import { uploadApi } from '/@/api/sys/upload';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();

  // 消息提示
  const { createMessage } = useMessage();

  // 获取用户信息 store
  const userStore = useUserStore();

  // 表单配置和注册
  const [register, { setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: baseSetschemas,
    showActionButtonGroup: false,
  });

  // 头像信息，使用默认头像或用户自定义头像
  const avatar = computed(() => {
    const { avatar } = userStore.getUserInfo;
    return avatar || headerImg;
  });

  // 更新头像方法
  function updateAvatar(src: string) {
    const userInfo = userStore.getUserInfo;
    userInfo.avatar = src;
    userStore.setUserInfo(userInfo);
  }

  // 提交表单方法
  function handleSubmit() {
    createMessage.success(t('common.updateSuccessText'));
  }

  // 在组件挂载时获取账户信息并设置表单的值
  onMounted(async () => {
    const data = await accountInfoApi();
    setFieldsValue(data);
  });
</script>

<style lang="less" scoped>
  .change-avatar {
    img {
      display: block;
      margin-bottom: 15px;
      border-radius: 50%;
    }
  }
</style>
